package com.chujian.gateway.filter;

import com.chujian.framework.starter.log.properties.TraceLogProperties;
import com.chujian.framework.starter.log.trace.MDCTraceUs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 生成日志链路追踪id，并传入header中
 *
 * @author chujian
 * @since 2021-12-13
 */
@Component
public class TraceFilter implements GlobalFilter, Ordered {

    @Autowired
    private TraceLogProperties traceProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        if (traceProperties.getEnabled()) {
            //链路追踪id
            MDCTraceUs.addTrace();
            ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate()
                    .headers(h -> {
                        h.add(MDCTraceUs.TRACE_ID_HEADER, MDCTraceUs.getTraceId());
                        h.add(MDCTraceUs.SPAN_ID_HEADER, MDCTraceUs.getSpanId());
                    })
                    .build();
            ServerWebExchange build = exchange.mutate().request(serverHttpRequest).build();
            return chain.filter(build);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
